﻿using System;
using System.Linq;
using System.Xml.Linq;
using NUnit.Framework;

namespace DotNet.DevOps.Tasks.Tests.Extensions
{
    internal static class ConfigTestExtensions
    {
        internal static void AssertThatFileHasNodesWithKeyValuePair(this String filename, string nodeName, string keyValue, string valueValue, int numberOfExpectedMatches)
        {
            var xDoc = XDocument.Load(filename);

            var nodesFound = xDoc.Root.DescendantNodes().OfType<XElement>()
                .Where(baseNode => baseNode.Name == nodeName)
                    .DescendantNodes().OfType<XElement>()
                        .Where(addNode => addNode.Name=="add")
                        .Where(addNode => addNode.Attributes().Where(atr => atr.Name == "key" && atr.Value == keyValue).Count() == 1)
                        .Where(addNode => addNode.Attributes().Where(atr => atr.Name == "value" && atr.Value == valueValue).Count() == 1)
                            .Count();

            Assert.That(nodesFound, Is.EqualTo(numberOfExpectedMatches));
        }

        internal static void AssertThatFileHasNodesWithAttributeAndKeyValuePair(this String filename, string nodeName, string attName, string attValue, string keyAttName, string keyAttValue, int numberOfExpectedMatches)
        {
            var xDoc = XDocument.Load(filename);

            var nodesFound = xDoc.Root.DescendantNodes().OfType<XElement>()
                .Where(baseNode => baseNode.Name == nodeName)
                        .Where(addNode => addNode.Attributes().Where(atr => atr.Name == attName && atr.Value == attValue).Count() == 1)
                           .DescendantNodes().OfType<XElement>()
                                .Where(addNode => addNode.Name == "level")
                                .Where(addNode => addNode.Attributes().Where(atr => atr.Name == keyAttName && atr.Value == keyAttValue).Count() == 1)
                                    .Count();

            Assert.That(nodesFound, Is.EqualTo(numberOfExpectedMatches));
        }

        internal static void AssertThatFileHasNodesWithNameAndKeyValuePair(this String filename, string nodeName, string keyAttName, string keyAttValue, int numberOfExpectedMatches)
        {
            var xDoc = XDocument.Load(filename);

            var nodesFound = xDoc.Root.DescendantNodes().OfType<XElement>()
                .Where(baseNode => baseNode.Name == nodeName)
                           .DescendantNodes().OfType<XElement>()
                                .Where(addNode => addNode.Name == "level")
                                .Where(addNode => addNode.Attributes().Where(atr => atr.Name == keyAttName && atr.Value == keyAttValue).Count() == 1)
                                    .Count();

            Assert.That(nodesFound, Is.EqualTo(numberOfExpectedMatches));
        }
    }
}
